package com.common.base.app.extras

import android.content.SharedPreferences
import com.google.gson.Gson
import java.lang.Double.doubleToLongBits
import java.lang.Double.longBitsToDouble

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：26/8/2025
 *
 * 描述：SharedPreferences扩展函数
 *
 * 修订历史：
 *
 */
fun SharedPreferences.Editor.putDouble(key: String, value: Double): SharedPreferences.Editor {
    return putLong(key, doubleToLongBits(value))
}

fun SharedPreferences.getDouble(key: String, defaultValue: Double): Double {
    return longBitsToDouble(getLong(key, doubleToLongBits(defaultValue)))
}

fun <T> SharedPreferences.Editor.putParcelable(key: String, value: T): SharedPreferences.Editor {
    val gson = Gson()
    val jsonString = gson.toJson(value)
    return putString(key, jsonString)
}

inline fun <reified T> SharedPreferences.getParcelable(key: String): T? {
    val gson = Gson()
    val jsonString = getString(key, null)
    return if (jsonString != null) {
        try {
            gson.fromJson(jsonString, T::class.java)
        } catch (e: Exception) {
            null
        }
    } else {
        null
    }
}